package com.lottery.thrift;

import java.lang.reflect.Method;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.springframework.util.ReflectionUtils;

import com.lottery.api.IThriftEntryProcesser;
import com.lottery.constant.GlobalConstants;
import com.lottery.pojo.thrift.service.config.Base;
import com.lottery.util.SpringUtil;

public class ThriftClient {

  public static String callService(Class<? extends Base> clz, String service, String method, String params) {
    String res = null;
    try {
      String name = clz.getSimpleName().toLowerCase();
      Object bean = SpringUtil.getApplicationContext().getBean(name);
      Method addressMethod = ReflectionUtils.findMethod(bean.getClass(), "getAddress");
      Method portMethod = ReflectionUtils.findMethod(bean.getClass(), "getPort");

      Object address = ReflectionUtils.invokeMethod(addressMethod, bean);
      Object port = ReflectionUtils.invokeMethod(portMethod, bean);

      TTransport transport = new TSocket(String.valueOf(address), Integer.parseInt(String.valueOf(port)));
      TProtocol protocol = new TBinaryProtocol(transport);
      TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, GlobalConstants.THRIFT_SERVICE_NAME);
      IThriftEntryProcesser.Client client = new IThriftEntryProcesser.Client(mp);
      transport.open();
      res = client.entry(service, method, params);
      transport.close();
    } catch (TException e) {
      e.printStackTrace();
    }
    return res;
  }

  public static String callService(Class<? extends Base> clz, String service, String method) {
    return callService(clz, service, method, null);
  }

}
